package com.sprinboot_vue.blog_springboot.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sprinboot_vue.blog_springboot.entity.*;
import com.sprinboot_vue.blog_springboot.mapper.BlogMapper;
import com.sprinboot_vue.blog_springboot.repository.*;
import com.sprinboot_vue.blog_springboot.result.Result;
import com.sprinboot_vue.blog_springboot.result.ResultInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.spring.web.json.Json;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @author Thomas
 * @version 1.0
 * @date 2021/11/22 14:25
 */
@RestController
@RequestMapping("/blog")
@Api(tags = "博文管理")
public class BlogHandler {
    @Autowired
    private BlogRepository blogRepository;
    @Autowired
    private TypeRepository typeRepository;
    @Autowired
    private TagRepository tagRepository;
    @Autowired
    private Blog_fileRepository blog_fileRepository;
    @Autowired
    private BlogMapper blogMapper;

    @PostMapping("/saveBlog")
    @ApiOperation("保存博文")
    public Result saveBlog(@RequestBody Map<String,Object> map){
        //构造一个博文对象
        Blog blog=new Blog();
        //取出传过来的数据
        Map<String,Object> map1=(Map<String, Object>) map.get("blog_data");
        //对博文对象赋值
        //这是前端传来的数据
        blog.setTitle(map1.get("title")+"");
        blog.setContent_html(map1.get("content_html")+"");
        blog.setContent_markdown(map1.get("content_markdown")+"");
        blog.setResource(map1.get("resource")+"");
        blog.setType_(map1.get("type_")+"");
        blog.setUser_id(map1.get("user_id")+"");
        blog.setDesc_(map1.get("desc_")+"");
        //这是后端需要赋予的数据
        Date date = new Date();
        //这个time相当于博文的主键
        long time = date.getTime();
        blog.setId(time);
        blog.setTime_(BlogGetDate(date));
        blog.setView_(0);
        System.out.println(blog.toString());
        try {
            //这里给相应的type的type_number+1操作
            String type_str=blog.getType_();
            long type_id=(long)type_str.hashCode();
            //通过id取得对应的Type对象
            Optional<Type> byId = typeRepository.findById(type_id);
            Type type = byId.get();
            type.setType_number(type.getType_number()+1);
            typeRepository.save(type);
            //这里要给相应的tag标签的tag_number+1操作!!!!!
            String tag_string="";
            List<String> tag_list=(List<String>) map1.get("tag");
            for(int i=0;i<tag_list.size();i++){
                //得到博文对应的标签的字符串形式
                if(i==tag_list.size()-1){
                    tag_string+=tag_list.get(i);
                }else{
                    //使用5个#进行隔断
                    tag_string+=tag_list.get(i)+"#####";
                }
                //循环使tag的number+1操作
                Optional<Tag> tag_byId1 = tagRepository.findById((long) tag_list.get(i).hashCode());
                Tag tag = tag_byId1.get();
                tag.setTag_number(tag.getTag_number()+1);
                tagRepository.save(tag);
            }
            //给博文赋值 tag标签的字符串
            blog.setTag_(tag_string);
            //保存博文
            Blog save = blogRepository.save(blog);
            //最后记录日志
            Blog_file blog_file=new Blog_file();
            blog_file.setBlog_id(blog.getId());
            blog_file.setBlog_title(blog.getTitle());
            blog_file.setUser_id(blog.getUser_id());
            blog_file.setTime_(BlogGetDate(date));
            blog_fileRepository.save(blog_file);
            //给前端返回结果!!!
            return Result.success().codeAndmessage(ResultInfo.INSERT);
        }catch (Exception e){
            return Result.error().codeAndmessage(ResultInfo.ERROR);
        }
    }
    //获得当前的时间  2021.12.23 12:23:59
    private String BlogGetDate(Date date){
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        return df.format(date);
    }


    //用于查询博文使用，返回最新的5条博文!!!
    @GetMapping("/findAllByPageDesc/{page}/{pageSize}")
    @ApiOperation("查询博文使用，返回最新的5条博文")
    public Result findAllByPageDesc(@PathVariable("page") int page,@PathVariable("pageSize") int pageSize){
        Page<Blog> page_1=new Page<>(page,pageSize);
        try {
            List<Blog> blogs = blogMapper.FindALLPageByDesc(page_1);
            int countBlog = blogMapper.findCountBlog();
            return Result.error().codeAndmessage(ResultInfo.SUCCESS)
                    .date("data",blogs).date("countBlog",countBlog);
        }catch (Exception e){
            return Result.error().codeAndmessage(ResultInfo.ERROR);
        }
    }

    //修改博文
    @PostMapping("/updateBlog")
    @ApiOperation("修改博客")
    public Result saveBlog(@RequestBody Blog blog){
        //保存修改修改后的博文
        try{
            Blog save = blogRepository.save(blog);
            return Result.success().codeAndmessage(ResultInfo.SUCCESS);
        }catch (Exception e){
            return Result.error().codeAndmessage(ResultInfo.ERROR);
        }
    }

    //删除博文
    @DeleteMapping("deleteBlogById/{id}")
    @ApiOperation("通过id删除博文")
    public Result deleteBlogById(@PathVariable("id") long id){
        try {
            //这里还要删除归档中的笔记
            /**
             * 这里就不写了！！！！！！
             */
            blogRepository.deleteById(id);
            return Result.success().codeAndmessage(ResultInfo.SUCCESS);
        }catch (Exception e){
            return Result.error().codeAndmessage(ResultInfo.ERROR);
        }
    }

    //通过id得到博文信息 并实现阅读量+1操作
    @GetMapping("findByBlogid/{id}")
    @ApiOperation("通过id返回博文并实现阅读量+1")
    public Result findByBlogid(@PathVariable("id") long id){
        Optional<Blog> byId = blogRepository.findById(id);
        Blog blog = byId.get();
        if(byId!=null){
            //实现阅读量+1操作！！！！
            blog.setView_(blog.getView_()+1);
            blogRepository.save(blog);
            return Result.success().codeAndmessage(ResultInfo.SUCCESS).date("data",blog);
        }else{
            return Result.success().codeAndmessage(ResultInfo.ERROR);
        }
    }

    //限定分类的下分页返回博文
    @GetMapping("/LimitTypeFindBlog/{page}/{pageSize}/{type}")
    @ApiOperation("限定分类的下分页返回博文")
    public Result LimitTypeFindBlog(@PathVariable("page") int page,@PathVariable("pageSize") int pageSize,@PathVariable("type") String type){
        Page<Blog> page_1=new Page<>(page,pageSize);
        List<Blog> blogs = blogMapper.FindALLTypeByDesc(page_1, type);
        int number = blogMapper.FindALLTypeByNumber(type);
        return Result.success().codeAndmessage(ResultInfo.SUCCESS).date("data",blogs).date("countBlog",number);
    }

    //限定标签的情况下分页返回博文
    @GetMapping("/LimitTagAllBlog/{page}/{pageSize}/{tag}")
    @ApiOperation("限定标签的情况下返回博文(分页)")
    public Result LimitTagAllBlog(@PathVariable("page") int page,@PathVariable("pageSize") int pageSize,@PathVariable("tag") String tag){
        Page<Blog> page_1=new Page<>(page,pageSize);
        List<Blog> blogs = blogMapper.FindALLTagByDesc(page_1, tag);
        int number = blogMapper.FindALLTagByNumber(tag);
        return Result.success().codeAndmessage(ResultInfo.SUCCESS).date("data",blogs).date("countBlog",number);
    }
}
